package com.richfit.barcodesystem_cczt.fragments;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;

import com.bigkoo.alertview.AlertView;
import com.google.gson.reflect.TypeToken;
import com.richfit.barcodesystem_cczt.R;
import com.richfit.barcodesystem_cczt.activitis.Main;
import com.richfit.barcodesystem_cczt.activitis.adapters.BottomDialogMenuAdapter;
import com.richfit.barcodesystem_cczt.activitis.model.base.Result;
import com.richfit.barcodesystem_cczt.activitis.model.login.BottomMenuEntity;
import com.richfit.barcodesystem_cczt.databinding.FragmentUnpackingAndPackingBinding;
import com.richfit.barcodesystem_cczt.fragments.adapters.Unpack_Adapter;
import com.richfit.barcodesystem_cczt.fragments.base.BaseFragment;
import com.richfit.barcodesystem_cczt.fragments.model.ZBoxEntity;
import com.richfit.barcodesystem_cczt.network.OkHttpUtils;
import com.richfit.barcodesystem_cczt.utils.Urls;
import com.richfit.barcodesystem_cczt.utils.dialog.DialogHelper;
import com.richfit.barcodesystem_cczt.utils.toast.ToastUtil;
import com.richfit.barcodesystem_cczt.widget.RichAutoEditText;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class UnpackingAndPacking extends BaseFragment {
    private static final String TAG = "UnpackingAndPacking";
    private FragmentUnpackingAndPackingBinding binding;
    private String bizType;
    private Unpack_Adapter unpack_adapter;
    private List<ZBoxEntity.Detail> details;
    private List<ZBoxEntity.CommitUnPackLine> commitUnPackLines = new ArrayList<>();
    /**
     * 提交的参数设置
     */
    private ZBoxEntity.CommitUnPack commitUnPack = new ZBoxEntity.CommitUnPack();

    public UnpackingAndPacking(String bizType) {
        this.bizType = bizType;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentUnpackingAndPackingBinding.inflate(inflater, container, false);
        init();
        return binding.getRoot();
    }

    private void init() {
        initView();
        initData();
    }

    private void initView() {
//        binding.etBoxNum.setText("zbox-zyl-010001");
//        getRefData("zbox-zyl-010001", 0);
        //控件拖动
        setViewMove(binding.BtnLast);
        setViewMove(binding.BtnNext);
        setViewMove(binding.floatingButton);
    }

    private void initData() {
        binding.etBoxNum.setOnClickListener(v -> binding.etBoxNum.setText(""));
        //获取箱子信息
        binding.etBoxNum.setOnRichAutoEditTouchListener((view, text) -> {
            //查询前，置空
            setInit();
            binding.TXTBoxNum.setText("");
            binding.TXTBoxNum.setTag("");
            binding.etLocation.setText("");
            commitUnPackLines = new ArrayList<>();
            getRefData(text.trim(), 0);
        });
        binding.etTarBoxNum.setOnClickListener(v -> binding.etTarBoxNum.setText(""));
        binding.etTarBoxNum.setOnRichAutoEditTouchListener((view, text) -> {
            //查询前，置空装箱单和目标仓位
            binding.etTarLocation.setText("");
            binding.txtTarBoxNum.setText("");
            //删掉 目标箱号id
            commitUnPack.setTargetZboxLineId("");
            //目标箱号信息
            getRefData(text.trim(), 1);
        });
        binding.BtnNext.setOnClickListener(v -> {
            Log.i(TAG, "initData: " + gson.toJson(commitUnPackLines));
            //点击下一步之前，先判断是否有调整了数量
            if (commitUnPackLines.size() <= 0) {
                ToastUtil.showTextShort("没有调整数量，不能到下一步！");
                return;
            }
            //当前列表隐藏
            binding.LVDetail.setVisibility(View.GONE);
            // 目标箱号页面显示
            binding.LLTarget.setVisibility(View.VISIBLE);
            //下一步按钮，隐藏
            binding.BtnNext.setVisibility(View.GONE);
            //上一步按钮显示
            binding.BtnLast.setVisibility(View.VISIBLE);
            //保存按钮显示
            binding.floatingButton.setVisibility(View.VISIBLE);


//            binding.etTarBoxNum.setText("zbox-zyl-020001");
//            getRefData("zbox-zyl-020001", 1);
        });
        /**
         * 上一页
         */
        binding.BtnLast.setOnClickListener(v -> {
            setInit();
        });
        /**
         * 生成新箱号
         */
        binding.BtnCreateNewBox.setOnClickListener(v -> {
            //显示新箱号设置页面
            binding.icdNewBox.getRoot().setVisibility(View.VISIBLE);
            //隐藏旧箱号的页面
            binding.LLTarget.setVisibility(View.GONE);
            //显示上一步按钮，跳转到旧箱号页面
            binding.BtnLastNew.setVisibility(View.VISIBLE);
            binding.BtnLast.setVisibility(View.GONE);
            //设置装箱类别为创建新箱号
            commitUnPack.setNewBoxFlag("1");
        });
        /**
         * 跳转到旧箱号页面
         */
        binding.BtnLastNew.setOnClickListener(v -> {
            //感叹号，表示相反
            //!显示新箱号设置页面
            binding.icdNewBox.getRoot().setVisibility(View.GONE);
            //!隐藏旧箱号的页面
            binding.LLTarget.setVisibility(View.VISIBLE);
            //!显示上一步按钮，跳转到旧箱号页面
            binding.BtnLastNew.setVisibility(View.GONE);
            binding.BtnLast.setVisibility(View.VISIBLE);

            //!设置装箱类别为创建新箱号
            commitUnPack.setNewBoxFlag("0");
        });
        /**
         * 按钮点击
         */
        binding.floatingButton.setOnClickListener(v -> showChooseDialog());
    }

    private void setInit() {
        //感叹号，表示相反
        //!当前列表隐藏
        binding.LVDetail.setVisibility(View.VISIBLE);
        // !目标箱号页面显示
        binding.LLTarget.setVisibility(View.GONE);
        //!下一步按钮，隐藏
        binding.BtnNext.setVisibility(View.VISIBLE);
        //!上一步按钮显示
        binding.BtnLast.setVisibility(View.GONE);
        //!保存按钮显示
        binding.floatingButton.setVisibility(View.GONE);
    }

    @Override
    public void handleBarCodeScanResult(String type, String[] list) {
        if (list != null) {
            //获取当前焦点所在的控件
            View vFocus = this.getActivity().getWindow().getDecorView().findFocus();

            if (vFocus instanceof RichAutoEditText) {
                RichAutoEditText richAutoEditText = (RichAutoEditText) vFocus;
                if (richAutoEditText.getId() == binding.etBoxNum.getId()) {
                    //抬头 装箱单
                    binding.etBoxNum.setText(list[0]);
                    getRefData(list[0], 0);
                } else if (richAutoEditText.getId() == binding.etTarLocation.getId()) {
                    //采集  箱单
                    binding.etTarLocation.setText(list[0]);
                    getRefData(list[0], 1);
                }

            }
            ToastUtil.showTextShort(list[0]);
        }
    }

    /**
     * 查询箱单信息
     * type: 0:源箱号；1：目标箱号
     *
     * @param zboxBarcode
     */
    private void getRefData(String zboxBarcode, int type) {
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在查询装箱单信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_ZBOX_LINE + "?zboxBarcode=" + zboxBarcode, bo.cookie, new OkHttpUtils.NetCallBack() {

            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                ZBoxEntity.Line line = gson.fromJson(data, ZBoxEntity.Line.class);
                if (type == 0) {
                    //源箱号 显示
                    binding.TXTBoxNum.setText(line.getZboxNum());
                    binding.TXTBoxNum.setTag(line.getZboxBarcode());
                    binding.etLocation.setText(line.getLocation());
                    //判断是否正常可以拆项的类型
                    if (!line.getIsJoinType()) {
                        //不能进行拆箱
                        ToastUtil.showTextLong("当前箱号不能进行拆箱！");
                        binding.BtnNext.setVisibility(View.GONE);
                    } else if (!line.getIsTransFFlag()) {
                        //不能进行拆箱
                        ToastUtil.showTextLong("当前箱号:" + line.getTransfFlagName() + "不能进行拆箱！");
                        binding.BtnNext.setVisibility(View.GONE);
                    } else {
                        binding.BtnNext.setVisibility(View.VISIBLE);
                    }
                    commitUnPack.setZboxLineId(line.getId());
                    //查询明显
                    getBoxDetail(line.getId());
                } else if (type == 1) {
                    binding.etTarLocation.setText(line.getLocation());
                    binding.txtTarBoxNum.setText(line.getZboxNum());
                    binding.txtTarBoxNum.setTag(line.getZboxBarcode());
                    if (!line.getIsJoinType()) {
                        //不能进行拆箱
                        ToastUtil.showTextLong("当前箱号不能进行装箱！");
                        binding.floatingButton.setVisibility(View.GONE);
                        commitUnPack.setTargetZboxLineId("");
                        //设置保存类型为 旧箱子
                        commitUnPack.setNewBoxFlag("0");
                    } else if (!line.getIsTransFFlag()) {
                        //不能进行拆箱
                        ToastUtil.showTextLong("当前箱号:" + line.getTransfFlagName() + "不能进行装箱！");
                        binding.floatingButton.setVisibility(View.GONE);
                        commitUnPack.setTargetZboxLineId("");
                        //设置保存类型为 旧箱子
                        commitUnPack.setNewBoxFlag("0");
                    } else {
                        binding.floatingButton.setVisibility(View.VISIBLE);
                        //查询成功后，保存目标箱号
                        commitUnPack.setTargetZboxLineId(line.getId());
                        //设置保存类型为 旧箱子
                        commitUnPack.setNewBoxFlag("0");
                    }

                }
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    private void getBoxDetail(String boxId) {
        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在获取装箱单详情信息");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doGet(Urls.URL_ZBOX_DETAIL + "?zboxLineId=" + boxId, bo.cookie, new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
                String data = gson.toJson(result.getData());
                details = gson.fromJson(data, new TypeToken<List<ZBoxEntity.Detail>>() {
                }.getType());

                unpack_adapter = new Unpack_Adapter(getActivity(), details);
                binding.LVDetail.setAdapter(unpack_adapter);
                unpack_adapter.setOnItemEditTextListener((editText, position) -> setOnItemEditText(editText, position));
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }

    private void setOnItemEditText(EditText editText, int position) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() <= 0) {
                    return;
                }
                //输入的数量
                BigDecimal moveq = new BigDecimal(s.toString());
                if (moveq.compareTo(BigDecimal.ZERO) == 0) {
                    ToastUtil.showTextShort("调整的数量不能为0！");
                    return;
                }
                //当前箱单的数量
                BigDecimal inq = details.get(position).getInQuantity();
                if (moveq.compareTo(inq) == 1) {
                    editText.setText(inq.toString());
                    moveq = inq;
                    ToastUtil.showTextShort("调整的数量不能大于箱单数量,已自动设置为箱单数量！");
                }
                //先判断列表中是否存在当前箱号
                boolean isExt = false;
                for (int i = 0; i < commitUnPackLines.size(); i++) {
                    ZBoxEntity.CommitUnPackLine commitUnPackLine = commitUnPackLines.get(i);
                    if (commitUnPackLine.getZboxDetailId().equals(details.get(position).getId())) {
                        //存在，更新调整数量
                        commitUnPackLines.get(i).setMoveQuantity(moveq);
                        isExt = true;
                        break;
                    }
                }
                if (!isExt) {
                    //不存在，则新增
                    ZBoxEntity.CommitUnPackLine commitUnPackLine = new
                            ZBoxEntity.CommitUnPackLine();
                    commitUnPackLine.setMaterialNum(details.get(position).getMaterialNum());
                    commitUnPackLine.setZboxDetailId(details.get(position).getId());
                    commitUnPackLine.setMoveQuantity(moveq);
                    commitUnPackLines.add(commitUnPackLine);
                }


            }
        });
    }

    /**
     * 分箱单明显-过账
     */
    private void showChooseDialog() {
        View rootView = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog_bottom_menu, null);
        GridView menu = rootView.findViewById(R.id.gd_menus);
        ArrayList<BottomMenuEntity> items = new ArrayList<>();
        BottomMenuEntity item = new BottomMenuEntity();
        item.setMenuName("保存");
        item.setMenuImageRes(R.mipmap.icon_data_submit);
        items.add(item);
        BottomDialogMenuAdapter adapter = new BottomDialogMenuAdapter(this.getContext(), items);
        menu.setAdapter(adapter);
        Dialog dialog = setDialog(rootView);
        menu.setOnItemClickListener((adapterView, view, position, id) -> {
            dialog.dismiss();
            switch (position) {
                case 0:
                    //提交
                    Commit();
                    break;

                default:
                    break;
            }

        });
    }

    AlertView alertView;

    private void Commit() {

        //判断是否对源箱子进行拆分操作
        if (commitUnPackLines.size() <= 0) {
            ToastUtil.showTextShort("没有调整任何物料的数量！不能进行保存！");
            return;
        }
        //判断是否输入了有效的目标箱号
        if ("0".equals(commitUnPack.getNewBoxFlag())) {
            if (TextUtils.isEmpty(commitUnPack.getTargetZboxLineId())) {
                ToastUtil.showTextShort("请输入有效的目标箱号！");
                return;
            }
            //判断是否源箱号，目标箱号 相同
            if (commitUnPack.getZboxLineId().equals(commitUnPack.getTargetZboxLineId())) {
                ToastUtil.showTextShort("源箱号和目标箱号相同！");
                return;
            }
        } else if ("1".equals(commitUnPack.getNewBoxFlag())) {
            //记录是否有空的项
            StringBuilder stringBuilder = new StringBuilder();
            //判断是否输入了新的箱子信息
            ZBoxEntity.Line line_New = new ZBoxEntity.Line();
            //包装方式
            line_New.setPackingSpec(binding.icdNewBox.etPackageManner.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getPackingSpec())) {
                stringBuilder.append("包装方式,");
            }
            //长
            line_New.setLength(binding.icdNewBox.etLength.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getLength())) {
                stringBuilder.append("长,");
            }
            //宽
            line_New.setWidth(binding.icdNewBox.etWidth.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getWidth())) {
                stringBuilder.append("宽,");
            }
            //高
            line_New.setHeight(binding.icdNewBox.etHeight.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getHeight())) {
                stringBuilder.append("高,");
            }
            //体积
            line_New.setVolume(binding.icdNewBox.etVolume.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getVolume())) {
                stringBuilder.append("体积,");
            }
            //净重
            line_New.setNetWeight(binding.icdNewBox.etNetWeight.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getNetWeight())) {
                stringBuilder.append("净重,");
            }
            //毛重
            line_New.setGrossWeight(binding.icdNewBox.etGrossWeight.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getGrossWeight())) {
                stringBuilder.append("毛重,");
            }
            //仓位
            line_New.setLocation(binding.icdNewBox.etLocation.getText().toString().trim());
            if (TextUtils.isEmpty(line_New.getLocation())) {
                stringBuilder.append("仓位,");
            }
            if (!TextUtils.isEmpty(stringBuilder.toString())) {
                ToastUtil.showTextShort(stringBuilder + "不能为空！");
                return;
            }
            commitUnPack.setNewBox(line_New);
        } else {
            ToastUtil.showTextShort("请输入目标箱号或者新增箱号！");
            return;
        }
        //整合数据
        commitUnPack.setRefLines(commitUnPackLines);
        String wl = "";
        for (ZBoxEntity.CommitUnPackLine packLine : commitUnPackLines) {
            wl += "物料：" + packLine.getMaterialNum() + ",调整数量：" + packLine.getMoveQuantity() + "\n";
        }
        String msg = "源箱号：" + binding.TXTBoxNum.getTag().toString() + "\n"
                + wl + "\n"
                + "目标箱号：" +
                ("0".equals(commitUnPack.getNewBoxFlag()) ? binding.txtTarBoxNum.getTag().toString() : "创建新箱号");
        alertView = new AlertView("提示", msg, null,
                new String[]{"确定", "取消"}, null, this.getActivity(),
                AlertView.Style.Alert, (o, position1) -> {

            alertView.dismiss();
            if (position1 == 0) {
                Unpack_Commit(commitUnPack);
            }
        });
        alertView.show();
    }

    void Unpack_Commit(ZBoxEntity.CommitUnPack commit) {
        commit.setCommitType("SUBMIT");
        commit.setBizType("MOVE_MATERIAL");
        Log.i(TAG, "Unpack_Commit: " + gson.toJson(commit));

        DialogHelper dialogHelper = new DialogHelper(this.getActivity());
        dialogHelper.showLoadingDialog("正在提交");
        OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
        okHttpUtils.doPostJson(Urls.URL_ZBOX_MOVE, bo.cookie, gson.toJson(commit), new OkHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Result result) {
                dialogHelper.dismissDialog();
//                String data = gson.toJson(result.getData());
//                {"info":"操作成功","status":"ok"}
//                数据全部清空，焦点定在台头页面
                ToastUtil.showTextShort("保存成功！");
                Main main = (Main) getActivity();
                main.setFragments(bizType);
            }

            @Override
            public void onFailure(Exception e) {
                dialogHelper.dismissDialog();
            }
        });
    }
}